<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneHidden">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="mark">
        <el-select v-model="queryParams.mark" placeholder="是否备注" clearable>
          <el-option key="0" label="无备注" value="0" />
          <el-option key="1" label="有备注" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in pms_publish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别：0->未知；1->男；2->女" clearable>
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker clearable
          v-model="queryParams.birthday"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择生日">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="推广员id" prop="spreadUid">
        <el-input
          v-model="queryParams.spreadUid"
          placeholder="请输入推广员id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          size="small"
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          :clearable="true"
          :picker-options='pickerOptions'
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ums:member:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="true"/>
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="phoneHidden" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="pms_publish_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar" width="100">
          <template #default="scope">
              <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
          </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="生日" align="center" prop="birthday" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="integral" />
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template v-slot="scope">
          <span class="mr10">{{scope.row.mark}}</span>
          <i class="el-icon-edit pointer" @click="showUpdateMark(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="data" @click="showStatistics(scope.row)" v-hasPermi="['ums:member:statistics']">查看数据</el-button>
            <el-button type="text" icon="order" @click="goOrder(scope.row)" v-hasPermi="['oms:order:query']">查看下单</el-button>
            <el-button type="text" icon="shoppCart" @click="goCart(scope.row)" v-hasPermi="['ums:memberCart:list']">查看购物车</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!--  统计  -->
    <el-dialog :title="statisticsObj.title" :visible.sync="statisticsObj.open" width="500px" append-to-body>
      <el-descriptions direction="vertical" :column="2" border>
        <el-descriptions-item label="购物车数">{{ statisticsObj.data.cartCount }}</el-descriptions-item>
        <el-descriptions-item label="订单数">{{ statisticsObj.data.orderCount }}</el-descriptions-item>
        <el-descriptions-item label="下单金额">￥{{ statisticsObj.data.orderAmount.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="售后数">{{ statisticsObj.data.aftersaleCount }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <el-dialog title="修改备注" :visible.sync="remarkModal.visible" width="30%" append-to-body>
      <el-input type='textarea' :rows='3' placeholder='请输入内容' v-model='remarkModal.mark'/>
      <span class="dialog-footer" slot="footer">
        <el-button @click="remarkModal.visible = false">取 消</el-button>
        <el-button type='primary' @click='updateRemark'>确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script setup name="Member">
import { listMember, getMember, delMember, addMember, updateMember } from "@/api/ums/member";

import {useRouter} from "vue-router";
const router = useRouter();

const { proxy } = getCurrentInstance();
const { sys_user_sex, pms_publish_status } = proxy.useDict('sys_user_sex', 'pms_publish_status');

const memberList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const statisticsObj = ref({open: false})
const remarkModal = ref({visible: false})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickname: undefined,
    password: undefined,
    phoneHidden: undefined,
    mark: undefined,
    status: undefined,
    avatar: undefined,
    gender: undefined,
    city: undefined,
    province: undefined,
    country: undefined,
    birthday: undefined,
    spreadUid: undefined,
    spreadTime: undefined,
    level: undefined,
    integral: undefined,
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
    nickname: [
      { required: true, message: "昵称不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    phoneEncrypted: [
      { required: true, message: "加密手机号不能为空", trigger: "blur" }
    ],
    phoneHidden: [
      { required: true, message: "隐藏前三位后四位的手机号不能为空", trigger: "blur" }
    ],
    mark: [
      { required: true, message: "用户备注不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    avatar: [
      { required: true, message: "头像不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别：0->未知；1->男；2->女不能为空", trigger: "change" }
    ],
    city: [
      { required: true, message: "用户所在城市不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "用户所在省份不能为空", trigger: "blur" }
    ],
    country: [
      { required: true, message: "用户所在国家不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "公众号运营者对粉丝的备注，公众号运营者可在微信公众平台用户管理界面对粉丝添加备注不能为空", trigger: "blur" }
    ],
    birthday: [
      { required: true, message: "生日不能为空", trigger: "blur" }
    ],
    spreadUid: [
      { required: true, message: "推广员id不能为空", trigger: "blur" }
    ],
    spreadTime: [
      { required: true, message: "推广员关联时间不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "等级不能为空", trigger: "blur" }
    ],
    integral: [
      { required: true, message: "用户剩余积分不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询会员信息列表 */
function getList() {
  loading.value = true;
  listMember(queryParams.value).then(response => {
    memberList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    nickname: undefined,
    password: undefined,
    phoneEncrypted: undefined,
    phoneHidden: undefined,
    mark: undefined,
    status: undefined,
    avatar: undefined,
    gender: undefined,
    city: undefined,
    province: undefined,
    country: undefined,
    remark: undefined,
    birthday: undefined,
    spreadUid: undefined,
    spreadTime: undefined,
    level: undefined,
    integral: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined
  };
  proxy.resetForm("memberRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加会员信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getMember(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改会员信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["memberRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateMember(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addMember(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除会员信息编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delMember(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ums/member/export', {
    ...queryParams.value
  }, `member_${new Date().getTime()}.xlsx`)
}

function showUpdateMark(record){
  remarkModal.value = {
    visible: true,
    mark: record.mark,
    memberId: record.id
  }
}

/**
 * 修改备注
 */
function updateRemark(){
  // updateUmsMemberMark({id:this.remarkModal.memberId,mark:this.remarkModal.mark})
  //   .then(res=>{
  //     if (res > 0) {
  //       this.$message.success('修改成功');
  //       this.remarkModal.visible = false;
  //       const obj = this.umsMemberList.filter(it=>it.id === this.remarkModal.memberId)[0]
  //       obj.mark = this.remarkModal.mark;
  //     } else {
  //       this.$message.success('修改失败');
  //     }
  //   })
}

function goOrder(row){
  // decryptedPhone(phone).then(res => {
    this.$router.push({
      path: '/order/order',
      query: {
        // phone: res
        memberId: row.id
      }
    })
  // })
}

function goCart(row){
  // decryptedPhone(phone).then(res => {
    router.push({
      path: '/member/shoppingCart',
      query: {
        // phone: res
        memberId: row.id
      }
    })
  // })
}

function showStatistics(row){
  // viewStatistics(memberId).then((response) => {
  //   statisticsObj.value.data = response.data
  //   statisticsObj.value.open = true
  // })
}


getList();
</script>
